<?php

namespace app\admin\controller\weixin;

use app\common\controller\Backend;
use app\admin\model\weixin\Config as ConfigModel;
use Exception;
use think\Db;

/**
 * 微信用户管理
 *
 * @icon fa fa-circle-o
 */
class Index extends Backend
{
    /**
     * User模型对象
     * @var \app\admin\model\weixin\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\weixin\Weixin;
        $this->modelconfig = new \app\admin\model\weixin\Config;
        $this->modelreply = new \app\admin\model\weixin\Reply;
        //获取酒店列表
        $this->newmodel = model('weixinNews');
        $newsList = $this->newmodel->where("status='normal'")->field("id,cate_name")->select();

        $this->view->assign('newslist', $newsList);

    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $list = collection($list)->toArray();

            unset($row);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    //删除公众号 同时删除配置表数据
    public function del($ids = ''){
        if ($this->request->isPost()) {
            $ids = $this->request->post("ids", [], 'trim');
            Db::startTrans();
            $eff1 = $this->model->where("wid={$ids}")->delete();
            $eff2 = $this->modelconfig->where("wx_id={$ids}")->delete();
            if($eff1 && $eff2){
                Db::commit();
                $this->success();
            }else{
                Db::rollback();
                $this->error("操作异常");
            }
        }
    }

    //添加应用配置页面 模板
    public function add(){


        $siteList = [];
        $groupList = ConfigModel::getGroupList();
        foreach ($groupList as $k => $v) {
            $siteList[$k]['name'] = $k;
            $siteList[$k]['title'] = $v;
            $siteList[$k]['list'] = [];
        }

        foreach ($this->modelconfig->where("wx_id=0")->select() as $k => $v) {
            if (!isset($siteList[$v['group']])) {
                continue;
            }
            $value = $v->toArray();
            $value['title'] = __($value['title']);
            if (in_array($value['type'], ['select', 'selects', 'checkbox', 'radio'])) {
                $value['value'] = explode(',', $value['value']);
            }
            $value['content'] = json_decode($value['content'], true);
            $value['tip'] = htmlspecialchars($value['tip']);
            $siteList[$v['group']]['list'][] = $value;
        }
        $index = 0;
        foreach ($siteList as $k => &$v) {
            $v['active'] = !$index ? true : false;
            $index++;
        }


        $this->view->assign('siteList', $siteList);

        return $this->view->fetch();
    }

    //处理添加业务
    public function doadd(){
        if ($this->request->isPost()) {


            $row = $this->request->post("row/a", [], 'trim');
            if ($row) {
                try {
                    //数据存储到两个表中 fa_weixin  fa_weixin_config
                    Db::startTrans();
                    $row["createtime"] = time();
                    $eff1  = $this->model->insertGetId($row);//添加公众号表
                    $wxnewid = $row["wnesid"];
                    //获取自动推送模板
                    $autoinfo = $this->newmodel->where(["id"=>$wxnewid])->find()->toArray();
                    $rdarr["id"] = $autoinfo["id"];
                    $rdarr["title"] = $autoinfo["cate_name"];
                    $rdarr["description"] = $autoinfo["description"];
                    $rdarr["url"] = "http://".$_SERVER['SERVER_NAME']."/addons/weixin/index.html?wxid=".$eff1;
                    $rdarr["image"] = $autoinfo["image"];

                    $repalydata["key"] = "subscribe";
                    $repalydata["type"] = "news";
                    $repalydata["status"] = 1;
                    $repalydata["hide"] = 0;
                    $repalydata["wxid"] = $eff1;
                    $repalydata["data"] = json_encode($rdarr);

                    $eff3 = $this->modelreply->insertGetId($repalydata);
                    $eff4 = $this->model->where(["wid"=>$eff1])->update(["autoreplyid"=>$eff3]);

                    $configList = [];
                    foreach ($this->modelconfig->where("wx_id=0")->select() as $v) {

                        if (isset($row[$v['name']])) {
                            $value = $row[$v['name']];
                            if (is_array($value) && isset($value['field'])) {
                                $value = json_encode(ConfigModel::getArrayData($value), JSON_UNESCAPED_UNICODE);
                            } else {
                                $value = is_array($value) ? implode(',', $value) : $value;
                            }
                            $v['value'] = $value;
                            $v['wx_id'] = $eff1;
                            unset($v["id"]);//删除主键
                            $configList[] = $v->toArray();
                        }
                    }

                    $eff2 = $this->modelconfig->insertAll($configList);

                    if($eff1 && $eff2 && $eff3 && $eff4){
                        Db::commit();
                    }else{
                        Db::rollback();
                        $this->error("操作异常");
                    }

                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }

                $this->success("配置成功");

            }
            $this->error(__('Parameter %s can not be empty', ''));
        }



    }

    //编辑配置
    public function edit($ids = NULL){
        $ids = $this->request->param("ids");
        $info = $this->model->where("wid={$ids}")->field("name,autoreplyid,wnesid")->find();//添加公众号表


        $siteList = [];
        $groupList = ConfigModel::getGroupList();
        foreach ($groupList as $k => $v) {
            $siteList[$k]['name'] = $k;
            $siteList[$k]['title'] = $v;
            $siteList[$k]['list'] = [];
        }

        foreach ($this->modelconfig->where("wx_id={$ids}")->select() as $k => $v) {
            if (!isset($siteList[$v['group']])) {
                continue;
            }
            $value = $v->toArray();
            $value['title'] = __($value['title']);
            if (in_array($value['type'], ['select', 'selects', 'checkbox', 'radio'])) {
                $value['value'] = explode(',', $value['value']);
            }
            $value['content'] = json_decode($value['content'], true);
            $value['tip'] = htmlspecialchars($value['tip']);
            $siteList[$v['group']]['list'][] = $value;
        }
        $index = 0;
        foreach ($siteList as $k => &$v) {
            $v['active'] = !$index ? true : false;
            $index++;
        }
        $this->view->assign('siteList', $siteList);
        $this->view->assign('editid', $ids);
        $this->view->assign('name', $info["name"]);
        $this->view->assign('wnesid', $info["wnesid"]);

        return $this->view->fetch();
    }

    //处理编辑配置
    public function doedit(){
        if ($this->request->isPost()) {
            $row = $this->request->post("row/a", [], 'trim');
            $editid = $this->request->post('editid');

            if($row){
                try {
                    //数据存储到两个表中 fa_weixin  fa_weixin_config 判断是否修改了公众号推送id

                    $oldinfo = $this->model->where(["wid"=>$editid])->find()->toArray();

                    if($oldinfo["wnesid"] != $row["wnesid"]){ //修改了推送模板 删除原来的模板,重新创建

                        $eff1 = $this->modelreply->where(["wxid"=>$oldinfo["wid"]])->delete();

                        $wxnewid = $row["wnesid"];
                        //获取自动推送模板
                        $autoinfo = $this->newmodel->where(["id"=>$wxnewid])->find()->toArray();

                        $rdarr["id"] = $autoinfo["id"];
                        $rdarr["title"] = $autoinfo["cate_name"];
                        $rdarr["description"] = $autoinfo["description"];
                        $rdarr["url"] = "http://".$_SERVER['SERVER_NAME']."/addons/weixin/index.html?wxid=".$oldinfo["wid"];
                        $rdarr["image"] = $autoinfo["image"];

                        $repalydata["key"] = "subscribe";
                        $repalydata["type"] = "news";
                        $repalydata["status"] = 1;
                        $repalydata["hide"] = 0;
                        $repalydata["wxid"] = $oldinfo["wid"];
                        $repalydata["data"] = json_encode($rdarr);

                        $eff3 = $this->modelreply->insertGetId($repalydata);
                        $eff4 = $this->model->where(["wid"=>$oldinfo["wid"]])->update(["autoreplyid"=>$eff3]);

                    }


                    $row["updatetime"] = time();
                    $this->model->where("wid={$editid}")->update($row);//添加公众号表

                    $configList = [];
                    foreach ($this->modelconfig->where("wx_id={$editid}")->select() as $v) {

                        if (isset($row[$v['name']])) {
                            $value = $row[$v['name']];
                            if (is_array($value) && isset($value['field'])) {
                                $value = json_encode(ConfigModel::getArrayData($value), JSON_UNESCAPED_UNICODE);
                            } else {
                                $value = is_array($value) ? implode(',', $value) : $value;
                            }
                            $v['value'] = $value;
                            $configList[] = $v->toArray();
                        }
                    }

                    $this->modelconfig->saveAll($configList);

                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }

                $this->success("配置编辑成功");

            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
    }

}
